package com.ruoyi.eam.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.eam.doman.AssetImages;
import com.ruoyi.eam.service.IAssetImagesService;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;

@RestController
@RequestMapping("/file")
public class FileController extends BaseController {

    @Resource
    private RemoteFileService remoteFileService;
    @Autowired
    private IAssetImagesService assetImagesService;

    /**
     * 图片上传
     */
    @Log(title = "资产图片", businessType = BusinessType.INSERT)
    @PostMapping("/image")
    public AjaxResult image(@RequestParam("files") MultipartFile[] files,@RequestParam("assetId") Long assetId,@RequestParam("type") String type)
    {
        System.out.println("---files---:"+files);
        System.out.println("---assetId---:"+assetId);
        System.out.println("---type---:"+type);
        for (MultipartFile file : files) {
            if (!file.isEmpty())
            {
                String extension = FileTypeUtils.getExtension(file);
                if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION))
                {
                    return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
                }
                R<SysFile> fileResult = remoteFileService.upload(file);
                String url = fileResult.getData().getUrl();
                //业务操作,新增
                AssetImages assetImages = new AssetImages();
                assetImages.setImagesUrl(url);
                if (assetId == 0)
                {
                    if(type.equals("maintain")){
                        assetImages.setBizType("maintain");
                    }
                }else{
                    assetImages.setAssetId(assetId);
                }
                assetImagesService.insertAssetImages(assetImages);
            }
        }
        AjaxResult ajax = AjaxResult.success();
        return ajax;
    }
}
